﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;

namespace TFSLBALib
{
    public partial class TFSConnectForm : Form
    {
		public TeamFoundationServer TFS = null;

        public TFSConnectForm()
        {
            InitializeComponent();

            CheckNConnect.Tag = "Check";
        }

        private void CheckNConnect_Click(object sender, EventArgs e)
        {
			try
			{
    			if (CheckNConnect.Tag == "Check")
    			{
					TFS = DirectTFSConnect(TFSURL.Text);

					// Tag the button and change
					CheckNConnect.Tag = "Connect";
					CheckNConnect.Text = "Connect";
					CheckNConnect.DialogResult = DialogResult.OK;
					StatusLabel.Text = "Connexion correct, click the Connect button";
				}
			}
			catch (Exception)
			{
				StatusLabel.Text = "Connexion failed, verify the URL...";
			} 
        }

    	public static TeamFoundationServer DirectTFSConnect(String url)
    	{
			TeamFoundationServer tfs = null;

			try
			{
				tfs = TeamFoundationServerFactory.GetServer(url);
				tfs.EnsureAuthenticated();
			}
			catch (Exception ex)
			{
				try
				{
					tfs = TeamFoundationServerFactory.GetServer(url, new UICredentialsProvider());
					tfs.EnsureAuthenticated();
				}
				catch (Exception _ex)
				{
					throw new Exception("Connexion failed", _ex);
				}
			}

			return tfs;
    	}

    	private void TFSURL_TextChanged(object sender, EventArgs e)
		{
			CheckNConnect.Tag = CheckNConnect.Text = "Check";
			CheckNConnect.DialogResult = DialogResult.None;
			StatusLabel.Text = "Enter a valid URL (i.e. \"HTTP://TFS01:8080\")";
		}
    }
}
